package common.utils;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.Base64;

public class AESUtil {

    private static final String ALGORITHM = "AES";
    private static final String TRANSFORMATION = "AES/ECB/PKCS5Padding";

    /**
     * 加密方法
     *
     * @param data 需要加密的数据
     * @param password 密码（任意长度）
     * @return 加密后的Base64编码字符串
     */
    public static String encrypt(String data, String password) throws Exception {
        SecretKeySpec secretKey = generateKey(password);
        Cipher cipher = Cipher.getInstance(TRANSFORMATION);
        cipher.init(Cipher.ENCRYPT_MODE, secretKey);
        byte[] encryptedBytes = cipher.doFinal(data.getBytes(StandardCharsets.UTF_8));
        return Base64.getEncoder().encodeToString(encryptedBytes);
    }

    /**
     * 解密方法
     *
     * @param encryptData 加密后的Base64编码字符串
     * @param password 密码（任意长度）
     * @return 解密后的原始字符串
     */
    public static String decrypt(String encryptData, String password) throws Exception {
        SecretKeySpec secretKey = generateKey(password);
        Cipher cipher = Cipher.getInstance(TRANSFORMATION);
        cipher.init(Cipher.DECRYPT_MODE, secretKey);
        byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(encryptData));
        return new String(decryptedBytes, StandardCharsets.UTF_8);
    }

    /**
     * 根据密码生成AES密钥
     *
     * @param password 密码（任意长度）
     * @return 符合AES要求的密钥
     */
    private static SecretKeySpec generateKey(String password) throws Exception {
        // 使用SHA-256哈希算法将密码转换为32字节的密钥
        MessageDigest digest = MessageDigest.getInstance("SHA-256");
        byte[] keyBytes = digest.digest(password.getBytes(StandardCharsets.UTF_8));
        return new SecretKeySpec(keyBytes, ALGORITHM);
    }

    public static void main(String[] args) {
        try {
            String password = "666666"; // 任意长度的密码
            String originalData = "Hello, AES!";

            // 加密
            String encryptedData = encrypt(originalData, password);
            System.out.println("Encrypted Data: " + encryptedData);

            // 解密
            String decryptedData = decrypt("U2FsdGVkX1+3Q9Z7Z6Q8Z7Z6Q8Z7Z6Q8Z7Z6Q8Z7Z6Q8=", password);
            System.out.println("Decrypted Data: " + decryptedData);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
